<template>
<div>
  <!-- 订单打包diaolog start -->
  <packaging
    v-if="packaingVisible"
    :popupVisible="packaingVisible"
    :tsareacode="detail.tsareacode"
    :detail="detail"
    @close="close('packaing')"
    @callback="packgingCallback">
  </packaging>
  <!-- 订单打包diaolog end -->

  <!-- 录入包材展示 dialog 开始 -->
  <scanDetail
    v-if="scanDetailVisible"
    :popupVisible="scanDetailVisible"
    :quantity="totalQuanlity"
    :handledData="handledData"
    @close="close('scanDetail')"
    @scan="handleScanEvent">
  </scanDetail>
  <!-- 录入包材展示 dialog 结束 -->

  <!-- 扫描录入 dialog 开始 -->
  <scanEvent
    v-if="scanEventVisible"
    :popupVisible="scanEventVisible"
    :quantityData="quantityData"
    :list="packagingOrderList"
    @close="close('scanEvent')"
    @back="scanEventBack"
    @callback="scanEventCallback">
  </scanEvent>
  <!-- 扫描录入 dialog 结束 -->

</div>
</template>
<script>
import { getLodop } from '@/utils/LodopFuncs'
import {formValidate} from '@/assets/mixins/rule/packaging-validate'
import { printInfo } from '@/utils/printReceipts'
export default {
  name:'packaging-popup',
  props:['popupVisible','detail','pacakingData'],
  mixins:[formValidate],
  data(){
    return {
      formInline:{
        tsareacode:''
      },

      packagingid:'',
      subOrderInputList:[],

      packaingVisible:false, // 控制打包dialog显示隐藏
      packaingData:undefined,

      scanDetailVisible:false, // 控制扫描详情dialog显示隐藏
      totalQuanlity:0, // 运单子单总数量
      handledQuanlity:0, // 已处理过的子单数量
      handledData:[], // 已经处理过的子单数据
      scanDetailData:undefined,

      scanEventVisible:false, // 控制扫描Event dialog显示隐藏
      packagingOrderList:[], // 当前运单下的所有子单信息
      quantityData:undefined, // 当前处理运单的数量信息（总数量，已处理过的数量）

      scanVisible:false,
      btnLoading:false // 控制按钮loading，防止重复提交
    }
  },
  mounted(){
    this.formInline.tsareacode = this.tsareacode

    if(this.detail.waybillstatus === 1){ // 已申请
      this.getPackagingData()
    } else {
      this.packaingVisible=true
    }
  },
  components:{
    packaging:()=>import('./module/packaging'),
    scanDetail:()=>import('./module/scanDetail'),
    scanEvent:()=>import('./module/scanEvent')
  },
  methods:{
    close(popupName){
      if(popupName === 'packaing'){ // 打包dialog，点击关闭，不用判断
        this[`${popupName}Visible`] = false
        this.$emit('close')
        this.$emit('callback')
      } else {
        this.$confirm(this.$t('m.packaging.notice'), this.$t('m.noticemessage'), {
          confirmButtonText:this.$t('m.confirm'),
          cancelButtonText:this.$t('m.cancel'),
          type:'warning'
        }).then(() => {
          this.callbackMessage(this.$t('m.packaging.outsuccess'),'success')
          this[`${popupName}Visible`] = false
          this.$emit('close')
          this.$emit('callback')
        }).catch(() => {
          this.callbackMessage(this.$t('m.packaging.state3'),'info')
        })
      }
    },
    // 根据打包单id获取打包详情
    getPackagingData(){
      let options = {
        method:'get',
        url:`/packaging/${this.detail.id}`
      }
      this.$axios(options).then(({ data }) => {
        this.assignment(data)
      })
    },
    // 打包dialog，输入运单数量后，回调
    packgingCallback(data){
      this.packaingVisible = false
      this.assignment(data)
    },
    // 整合数据，赋值
    assignment(data){
      this.packagingOrderList = data.packagingSubOrderVoList // 当前运单下的所有子单信息
      this.totalQuanlity = data.quantity
      this.packagingid = data.id
      this.scanDetailVisible = true
    },
    // 打开输入包材数量的dialog
    handleScanEvent(data){
      this.scanDetailVisible = false
      this.quantityData = data
      this.scanEventVisible = true
    },
    // 扫描Event back，返回上一步
    scanEventBack(){
      this.scanEventVisible = false
      this.scanDetailVisible = true
    },
    // 扫描Event dialog，回调
    scanEventCallback(data){
      this.packagingOrderList = this.packagingOrderList.slice(data.list.length)
      // 判断是否有重复的packagename
      let isDuplicate = this.handledData.findIndex((item)=> item.packagename === data.packagename)
      // 记录当前处理的子单数据
      if(isDuplicate===-1){ // 如果不存在，直接推入记录
        this.handledData.push(data)
      } else { // 如果存在，在存在项中推入数据
        this.$set(this.handledData[isDuplicate],'list',[...this.handledData[isDuplicate].list,...data.list])
      }
      this.scanEventVisible = false

      let printId = data.list.map(item => item.packagingsuborderid)
      if(this.packagingOrderList.length){ // 继续进行扫描流程
        // 扫描子单打印
        this.detailPrint(printId)
        this.scanDetailVisible = true

      } else { // 当剩余子单数量===0，调取接口

        let subOrderInputList = this.handledData.reduce((prev,next)=>prev.concat(...next.list),[]) // 根据接口字段要求，处理数据
        let data = {
          packagingid:this.packagingid,
          subOrderInputList
        }
        let timeout = 30000
        let options = {
          method:'post',
          url:`/packagingsuborder/handle`,
          data,
          timeout:timeout
        }
        this.$axios(options).then((data) => {
          this.detailPrint(printId)
          let tempData = data.data
          if(tempData){
            this.$confirm(this.$t('m.packaging.ifprintdeliverynote'), this.$t('m.noticemessage'), {
              confirmButtonText:this.$t('m.confirm'),
              cancelButtonText:this.$t('m.cancel'),
              type:'warning'
            }).then(() => {
              printInfo(tempData)
            }).catch(() => {

            })
          }
          this.$emit('success')
          this.$emit('close')
        }).catch(() => {
          this.$emit('close')
        })
      }
    },
    // 扫描录入打印
    detailPrint(printId){
      let LODOP = getLodop()
      let options = {
        method:'post',
        url:'/printtemplate/query',
        data:{ids:printId,templateName:'packingSubOrder'}
      }
      this.$axios(options).then(({data})=> {
        eval(data)
        LODOP.SET_PRINT_PAGESIZE(1, '52mm', '85mm', '')
        LODOP.PRINT()
        // LODOP.PREVIEW()
      })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>